package cn.site.modules.cms.web;

import cn.site.core.mapper.JsonMapper;
import cn.site.core.web.BaseController;
import cn.site.modules.cms.entity.Site;
import cn.site.modules.cms.service.SiteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by ZGJ on 2015/3/5.
 */
@Controller
@RequestMapping(value = "/cms/site")
public class SiteController extends BaseController {

    @Autowired
    private SiteService siteService;

    @ResponseBody
    @RequestMapping(value = "")
    public Object getList() {
        List<Site> list = siteService.getList();
        JsonMapper jm = JsonMapper.getInstance();
        return jm.toJson(list);
    }

    @RequestMapping(value = "list")
    public String list(HttpServletRequest request, HttpServletResponse response) {
        List<Site> list = siteService.getList();
        request.setAttribute("list", list);

        request.setAttribute("msg", "this is site list page");

        return "modules/cms/siteList";
    }

    @RequestMapping(value = "form")
    public String form(Site site, Model model) {
        model.addAttribute("site", site);
        return "modules/cms/siteForm";
    }

    @RequestMapping(value = "save")
    public String save(Site site, Model model, RedirectAttributes redirectAttributes) {

        if (!beanValidator(model, site)) {
            return form(site, model);
        }

        siteService.save(site);
        addMessage(redirectAttributes, "保存站点'" + site.getName() + "'成功");

        return "redirect:list";
    }

    @RequestMapping(value = "delete")
    public String delete(int id, RedirectAttributes redirectAttributes) {

        siteService.delte(id);
        addMessage(redirectAttributes, "删除站点成功");

        return "redirect:list";
    }

}
